package com.ljkj.cordial.chat.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.nic.view.util.glide.GlideUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

/**
 * 生成多张结合头像
 */
public class PuzzleImageView extends android.support.v7.widget.AppCompatImageView {
    private final int marginWhiteWidth = 4; // 中间白色宽度
    private int width, height;
    private ExecutorService exec;

    public PuzzleImageView(Context context) {
        super(context);
        initSize();
        setBackgroundColor(Color.WHITE);
    }

    public PuzzleImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initSize();
        setBackgroundColor(Color.WHITE);
    }

    private void initSize() {
        if (width == 0) {
            width = TypedValue.complexToDimensionPixelOffset(48, getResources().getDisplayMetrics());
            height = TypedValue.complexToDimensionPixelOffset(48, getResources().getDisplayMetrics());
        }
    }

    public void setImageBackGrounds(String urls) {
        if (TextUtils.isEmpty(urls)) {
            return;
        }
        String[] sp = urls.split(",");
        if (sp != null) {
            List<String> list = new ArrayList<>();
            for (String s1 : sp) {
                list.add(s1);
            }
            setImageBackGround(list);
        }
    }

    /**
     * 设置头像 多个
     *
     * @param list
     */
    public void setImageBackGround(List<String> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        this.width = this.getLayoutParams().width;
        this.height = this.getLayoutParams().height;
        int len = list.size() > 9 ? 9 : list.size();
        if (exec == null || exec.isShutdown()) {
            exec = Executors.newSingleThreadExecutor();
        }
        exec.submit(new Runnable() {
            @Override
            public void run() {
                List<Bitmap> bitmapList = new ArrayList<>();
                for (int i = 0; i < len; i++) {
                    String uri = list.get(i);
                    Bitmap bitmap = null;
                    try {
                        bitmap = getHttpBitmap(ChatApp.getInstance(), uri);
                        bitmapList.add(bitmap);
                    } catch (ExecutionException e) {
//                        e.printStackTrace();
//                        JLog.d("失败 " + i);
                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                        JLog.d("失败 " + i);
                    }


                }
                if (((Activity) getContext()).isFinishing()) {
                    if (exec != null) {
                        exec.shutdownNow();
                    }
                    return;
                }
                ((Activity) getContext()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap bitmap = combimeImage(bitmapList);//getAvatar(bitmapList, width, height);
                        loadCropCircle(PuzzleImageView.this, bitmap);
                    }
                });
                if (exec != null) {
                    exec.shutdownNow();
                }
            }
        });
    }


    /**
     * 好友头像
     *
     * @param url
     * @param targetId
     */
    public void setFriendUrl(String url, String targetId) {
        this.width = this.getLayoutParams().width;
        this.height = this.getLayoutParams().height;
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(targetId)) {
            GlideUtil.getInstance().load(R.mipmap.pic_user_avatar_default_36dp, PuzzleImageView.this);
            return;
        }

        AlbumManageUtil.getInstance().downLoadFileFriendAvatar(url, targetId, new AlbumManageUtil.OnFileResponse() {
            @Override
            public void onResult(String path, String fileId) {
                if (TextUtils.isEmpty(fileId)) {
                    GlideUtil.getInstance().load(R.mipmap.pic_user_avatar_default_36dp, PuzzleImageView.this);
                    return;
                }
                File file = new File(fileId);
                if (!file.exists()) {
                    GlideUtil.getInstance().load(R.mipmap.pic_user_avatar_default_36dp, PuzzleImageView.this);
                    return;
                }
                Bitmap c = BitmapFactory.decodeFile(fileId);
                if (c == null) {
                    GlideUtil.getInstance().load(R.mipmap.pic_user_avatar_default_36dp, PuzzleImageView.this);
                    return;
                }
                String tag = (String) PuzzleImageView.this.getTag(com.nic.view.R.id.glide_image_id);
                if (TextUtils.isEmpty(tag) || tag.equals(url)) {
                    setTag(com.nic.view.R.id.glide_image_id, url);
                }
                loadCropCircle(PuzzleImageView.this, c);
            }
        });

    }

    public void setFriendPath(String path, String url) {
        if (TextUtils.isEmpty(path)) {
            GlideUtil.getInstance().load(R.mipmap.pic_user_avatar_default_36dp, this);
            return;
        }
        String tag = (String) getTag(com.nic.view.R.id.glide_image_id);
        if (TextUtils.isEmpty(tag) || tag.equals(url)) {
            setTag(com.nic.view.R.id.glide_image_id, url);
        }
        GlideUtil.getInstance().load(path, this);
    }

    /**
     * 群头像
     *
     * @param urls
     * @param ids
     */
    public void setImageBackGround(String urls, String ids) {
        this.width = this.getLayoutParams().width;
        this.height = this.getLayoutParams().height;
//        if (TextUtils.isEmpty(urls) || TextUtils.isEmpty(ids)) {
//            setImageResource(R.mipmap.pic_group_avatar_default_58dp);
//            return;
//        }
        if (!urls.contains(",")) {
            setImageBackGroundMix(urls, ids);
            return;
        }
        String[] v = urls.split(",");
        String[] d = ids.split(",");
        int length = v.length;
        if (d.length < v.length)
            length = d.length;
        try {
            List<Bitmap> bitmaps = new ArrayList<>();
            AtomicInteger atomicInteger = new AtomicInteger();
            Map<Integer, Bitmap> qun = new HashMap<>();
            for (int i = 0; i < length; i++) {
                if (!TextUtils.isEmpty(v[i]) && !TextUtils.isEmpty(d[i])) {
                    int finalI = i;
                    AlbumManageUtil.getInstance().downLoadFileFriendAvatar(v[i], d[i], new AlbumManageUtil.OnFileResponse() {
                        @Override
                        public void onResult(String url, String fileId) {
                            if (!TextUtils.isEmpty(fileId)) {
                                if (atomicInteger.intValue() == v.length) {
                                    String tag = (String) getTag(com.nic.view.R.id.glide_image_id);
                                    if (TextUtils.isEmpty(tag) || tag.equals(urls)) {
                                        setTag(com.nic.view.R.id.glide_image_id, urls);
                                    }
                                }
                                mulFileResult(qun, fileId, bitmaps, atomicInteger, v.length, finalI);
                            } else {
                                atomicInteger.getAndIncrement();
                            }

                        }
                    });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 群头像
     */
    public void setImageBackGroundMix(String url, String id) {
        this.width = this.getLayoutParams().width;
        this.height = this.getLayoutParams().height;
        AlbumManageUtil.getInstance().downLoadFileFriendAvatar(url, id, new AlbumManageUtil.OnFileResponse() {
            @Override
            public void onResult(String url, String filePath) {
                if (TextUtils.isEmpty(filePath)) {
                    GlideUtil.getInstance().load(R.mipmap.pic_group_avatar_default_58dp, PuzzleImageView.this);
                    return;
                }
                File file = new File(filePath);
                if (!file.exists()) {
                    GlideUtil.getInstance().load(R.mipmap.pic_group_avatar_default_58dp, PuzzleImageView.this);
                    return;
                }
                String tag = (String) getTag(com.nic.view.R.id.glide_image_id);
                if (TextUtils.isEmpty(tag) || tag.equals(url)) {
                    setTag(com.nic.view.R.id.glide_image_id, url);
                }
                Bitmap bmp = BitmapFactory.decodeFile(filePath);
                if (bmp == null) {
                    GlideUtil.getInstance().load(R.mipmap.pic_group_avatar_default_58dp, PuzzleImageView.this);
                    return;
                }
                ArrayList<Bitmap> list = new ArrayList<>();
                list.add(bmp);
                Bitmap bitmap = combimeImage(list);
                loadCropCircle(PuzzleImageView.this, bitmap);
            }
        });
    }

    public void setGroupPaths(String paths) {
        this.width = this.getLayoutParams().width;
        this.height = this.getLayoutParams().height;
        String tag = (String) getTag(com.nic.view.R.id.glide_image_id);
        if (TextUtils.isEmpty(tag) || tag.equals(paths)) {
            setTag(com.nic.view.R.id.glide_image_id, paths);
        }
        List<Bitmap> bitmaps = new ArrayList<>();
        String p[] = paths.split(",");
        for (String path : p) {
            try {
                if (!TextUtils.isEmpty(path)) {
                    Bitmap bmp = BitmapFactory.decodeFile(path);
                    bitmaps.add(bmp);
                }
            } catch (Exception e) {
            }
        }
        if (bitmaps.isEmpty()) {
            GlideUtil.getInstance().load(R.mipmap.pic_group_avatar_default_58dp, this);
            return;
        }
        makeAvatar(bitmaps);

    }

//    public void setGroupTargetId(String targetId) {
//        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<ChatContentTable>() {
//            @Override
//            public void onAction(ChatContentTable obj) {
//                if (obj == null) {
//                    setImageResource(R.mipmap.pic_group_avatar_default_58dp);
//                    return;
//                }
//                setGroupPaths(obj.getTargetAvatarPath());
//            }
//
//            @Override
//            public ChatContentTable onThreadAction() {
//                ChatContentTable cct = ChatContentTable.queryRowByTargetIdNotNull(targetId, Canstants.GROUP_CHAT);
//                if (cct != null) {
//                    String[] v = GroupMemberTable.getAvatarEntityLoc(String.valueOf(targetId));
//                    if (v != null) {
//                        cct.setTargetMemberUserId(v[0]);
//                        cct.setTargetAvatarUrl(v[1]);
//                        cct.setTargetAvatarPath(v[2]);
//                        ChatContentTable.update(cct);
//                    }
//
//                    return cct;
//                }
//                return null;
//            }
//        });
//
//    }

    private void mulFileResult(Map<Integer, Bitmap> qun, String locPath, List<Bitmap> bitmaps, AtomicInteger atomicInteger, int count, int index) {
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Boolean>() {
            @Override
            public void onAction(Boolean obj) {
                if (obj.booleanValue()) {
                    List<Bitmap> nList = new ArrayList<>();
                    for (int i = 0; i < count; i++) {
                        if (qun.containsKey(i)) {
                            nList.add(qun.get(i));
                        }
                    }
                    makeAvatar(nList);
                }
            }

            @Override
            public Boolean onThreadAction() {
                atomicInteger.getAndIncrement();
//                AlbumTableBean b = AlbumTableBean.queryById(Long.parseLong(fileId));
//                if (b != null && !TextUtils.isEmpty(b.getMThumbPath())) {
                try {
                    if (!TextUtils.isEmpty(locPath)) {
                        Bitmap bmp = BitmapFactory.decodeFile(locPath);
                        qun.put(index, bmp);
                        bitmaps.add(bmp);
                    }
                } catch (Exception e) {
                }
//                }
                return atomicInteger.intValue() == count;
            }
        });
    }

    private void makeAvatar(List<Bitmap> bitmaps) {
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<List<Bitmap>>() {
            @Override
            public void onAction(List<Bitmap> obj) {
                try {
                    Bitmap bitmap = combimeImage(bitmaps);//getAvatar(bitmaps, width, height);
                    loadCropCircle(PuzzleImageView.this, bitmap);
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }

            @Override
            public List<Bitmap> onThreadAction() {
                return bitmaps;
            }
        });
    }

    /**
     * 生成群组头像
     *
     * @param bitmapList
     * @param width
     * @param height
     * @return
     */
    private Bitmap getAvatar(List<Bitmap> bitmapList, int width, int height) {
        if (width == 0) {
            width = TypedValue.complexToDimensionPixelOffset(48, getResources().getDisplayMetrics());
            height = TypedValue.complexToDimensionPixelOffset(48, getResources().getDisplayMetrics());
        }
        final Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        Canvas canvas = new Canvas(result);
        final int listSize = bitmapList.size();
        switch (listSize) {
            case 1:
                Bitmap _p11 = Bitmap.createScaledBitmap(bitmapList.get(0), width, height, false);
                canvas.drawBitmap(_p11, 0, 0, paint);
                break;
            case 2:
                // 比例缩放
                Bitmap _p21 = Bitmap.createScaledBitmap(bitmapList.get(0), width, height, false);
                Bitmap _p22 = Bitmap.createScaledBitmap(bitmapList.get(1), width, height, false);
                // 裁取中间部分(从x点裁取置顶距离)
                Bitmap __p21 = Bitmap.createBitmap(_p21, width / 4 + marginWhiteWidth / 2, 0, width / 2 - marginWhiteWidth / 2, height); // 中间留有1px白条
                Bitmap __p22 = Bitmap.createBitmap(_p22, width / 4 + marginWhiteWidth / 2, 0, width / 2 - marginWhiteWidth / 2, height); // 中间留有1px白条
                // 绘图
                canvas.drawBitmap(__p21, 0, 0, null);
                canvas.drawRect(new Rect(width / 2 - marginWhiteWidth / 2, 0, width / 2 + marginWhiteWidth / 2, height), paint);
                canvas.drawBitmap(__p22, width / 2 + marginWhiteWidth / 2, 0, null);
                break;
            case 3:
                // 1-图1
                Bitmap _p31 = Bitmap.createScaledBitmap(bitmapList.get(0), width, height, false);
                Bitmap __p31 = Bitmap.createBitmap(_p31, width / 4 + marginWhiteWidth / 2, 0, width / 2 - marginWhiteWidth / 2, height);
                // 2-图2,3
                Bitmap _p32 = Bitmap.createScaledBitmap(bitmapList.get(1), width / 2 - marginWhiteWidth / 2, height / 2 - marginWhiteWidth / 2, false);
                Bitmap _p33 = Bitmap.createScaledBitmap(bitmapList.get(2), width / 2 - marginWhiteWidth / 2, height / 2 - marginWhiteWidth / 2, false);
                // 3-拼接
                canvas.drawBitmap(__p31, 0, 0, null);
                canvas.drawRect(new Rect(width / 2 - marginWhiteWidth / 2, 0, width / 2 + marginWhiteWidth / 2, height), paint);
                canvas.drawBitmap(_p32, width / 2 + marginWhiteWidth / 2, 0, null);
                canvas.drawRect(new Rect(width / 2 + marginWhiteWidth / 2, height / 2 - marginWhiteWidth / 2, width, height / 2 + marginWhiteWidth / 2), paint);
                canvas.drawBitmap(_p33, width / 2 + marginWhiteWidth / 2, height / 2 + marginWhiteWidth / 2, null);
                break;
            case 4:
                // 比例缩放
                Bitmap _p41 = Bitmap.createScaledBitmap(bitmapList.get(0), width / 2 - marginWhiteWidth / 2, height / 2 - marginWhiteWidth / 2, false);
                Bitmap _p42 = Bitmap.createScaledBitmap(bitmapList.get(1), width / 2 - marginWhiteWidth / 2, height / 2 - marginWhiteWidth / 2, false);
                Bitmap _p43 = Bitmap.createScaledBitmap(bitmapList.get(2), width / 2 - marginWhiteWidth / 2, height / 2 - marginWhiteWidth / 2, false);
                Bitmap _p44 = Bitmap.createScaledBitmap(bitmapList.get(3), width / 2 - marginWhiteWidth / 2, height / 2 - marginWhiteWidth / 2, false);
                // 多图拼接
                canvas.drawBitmap(_p41, 0, 0, paint);
                canvas.drawRect(new Rect(width / 2 - marginWhiteWidth / 2, 0, width / 2 + marginWhiteWidth / 2, height), paint);
                canvas.drawBitmap(_p42, width / 2 + marginWhiteWidth / 2, 0, null);
                canvas.drawBitmap(_p43, 0, height / 2 + marginWhiteWidth / 2, null);
                canvas.drawRect(new Rect(0, height / 2 - marginWhiteWidth / 2, width, height / 2 + marginWhiteWidth / 2), paint);
                canvas.drawBitmap(_p44, width / 2 + marginWhiteWidth / 2, height / 2 + marginWhiteWidth / 2, null);
                break;
            default:
                break;
        }
        return result;
    }

    /**
     * 获取网络图片的Bitmap
     *
     * @param activity
     * @param uri
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static Bitmap getHttpBitmap(Context activity, String uri) throws
            ExecutionException, InterruptedException {
        return Glide.with(activity)
                .load(uri)
                .asBitmap()
                .into(1024, 1024)
                .get();
    }

    /**
     * 圆形加载图片
     * 加载 bitmap
     *
     * @param imageAware
     * @param bitmap
     */
    public static void loadCropCircle(ImageView imageAware, Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] bytes = baos.toByteArray();
//        int dp8 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, imageAware.getResources().getDisplayMetrics());
        int dp4 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, imageAware.getResources().getDisplayMetrics());
        Glide.with(ChatApp.getInstance())
                .load(bytes)
                .placeholder(imageAware.getDrawable()) //加载中
                .error(R.drawable.ic_loading_fail)//加载失败
                .fallback(R.drawable.ic_loading_fail)//加载为空
                .priority(Priority.HIGH)//加载的优先等级
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存类型
                .skipMemoryCache(false)
//                .bitmapTransform(new CropCircleTransformation(ChatApp.getInstance()))
                .bitmapTransform(new RoundedCornersTransformation(ChatApp.getInstance(), dp4, 0))
                .dontAnimate()
                .into(imageAware);
    }

    public Bitmap combimeImage(List<Bitmap> bitmaps) {
        if (width == 0 || height == 0) {
            width = TypedValue.complexToDimensionPixelOffset(48, getResources().getDisplayMetrics());
            height = TypedValue.complexToDimensionPixelOffset(48, getResources().getDisplayMetrics());
        }
        return combineImages(bitmaps, width, 6, Color.parseColor("#dbdfe0"));
    }

    /**
     * 进行图片组合
     *
     * @param bitmaps     图片列表
     * @param parentWidth 图片显示的宽度
     * @param padding     图片间距大小
     * @param borderColor 边框和间隙颜色
     * @return
     */
    public Bitmap combineImages(List<Bitmap> bitmaps, int parentWidth, int padding, int borderColor) {
        int size = bitmaps.size();
        // 根据图片数计算列数
        int maxColumn = getMaxColumn(size);
        // 计算图片行数
        // int maxRow = getMaxRow(size);

        // 图片实际占用宽度（去除padding）
        int valiableImageWidth = parentWidth - (maxColumn - 1) * padding;

        // 根据列数计算图片宽度和高度
        int imgWidth = valiableImageWidth / maxColumn;
        // int imgHeight = valiableImageWidth / maxColumn;

        // padding占据图片宽度的百分比
        float paddingPer = (float) padding / imgWidth;

        // 画布,空白大图
        Bitmap newBitmap = Bitmap.createBitmap(parentWidth, parentWidth, Bitmap.Config.ARGB_8888);

        // 获得各图片坐标
        List<PointF> points = getPointFlist(size, maxColumn, imgWidth, paddingPer);

        for (int i = 0; i < points.size(); i++) {
            // 生成指定大小的缩略图
            Bitmap thumBitmap = getThumbnailBitmap(bitmaps.get(i), imgWidth);
            // 组合成新的图片
            newBitmap = mixtureBitmap(newBitmap, thumBitmap, points.get(i));
        }

        if (borderColor != 0) {
            newBitmap = setBgAndBorder(newBitmap, borderColor, padding);
        }

        return newBitmap;
    }

    /**
     * 计算每一张图片的坐标点
     *
     * @param size       图片的数量
     * @param maxColumn  行数
     * @param imgWidth   每一张图片的宽度
     * @param paddingPer 图片中间的缝隙与图片宽度的百分比
     * @return
     */
    private static List<PointF> getPointFlist(int size, int maxColumn, float imgWidth, float paddingPer) {
        List<PointF> pointFList = new ArrayList<>();

        // 1张图片
        if (maxColumn == 1) {
            int xleft = 0;
            int xtop = 0;

            addPointF(pointFList, imgWidth, xleft, xtop);
        }
        // 2,3,4张图片
        else if (maxColumn == 2) {
            if (size == 2) {
                // 对应坐标 w == imgWidth
                // 0,w/2  w w/2

                for (int i = 0; i < size; i++) {
                    //计算左上角坐标
                    float xleft = 0;
                    float xtop = 0;
                    switch (i) {
                        case 0:
                            xleft = 0;
                            xtop = 1 / 2f;
                            break;
                        case 1:
                            xleft = 1 + paddingPer;
                            xtop = 1 / 2f;
                            break;
                    }

                    addPointF(pointFList, imgWidth, xleft, xtop);
                }
            } else if (size == 3) {
                // 对应坐标 w == imgWidth
                //  w/2,0
                // 0,w  w w
                for (int i = 0; i < size; i++) {
                    //计算左上角坐标
                    float xleft = 0;
                    float xtop = 0;

                    switch (i) {
                        case 0:
                            xleft = 1 / 2f;
                            xtop = 0;
                            break;
                        case 1:
                            xleft = 0;
                            xtop = 1 + paddingPer;
                            break;
                        case 2:
                            xleft = 1 + paddingPer;
                            xtop = 1 + paddingPer;
                            break;
                    }

                    addPointF(pointFList, imgWidth, xleft, xtop);
                }
            } else {
                // 对应坐标 w == imgWidth
                // 0,0  w 0
                // 0,w  w w

                for (int i = 0; i < size; i++) {
                    //计算左上角坐标
                    float xleft = 0;
                    float xtop = 0;

                    switch (i) {
                        case 0:
                        case 2:
                            xleft = 0;
                            xtop = i * (1 / 2f);
                            if (i == 2) {
                                xtop += paddingPer;
                            }
                            break;
                        case 1:
                        case 3:
                            xleft = 1 + paddingPer;
                            xtop = (i - 1) * (1 / 2f);
                            if (i == 3) {
                                xtop += paddingPer;
                            }
                            break;
                    }

                    addPointF(pointFList, imgWidth, xleft, xtop);
                }
            }
        }
        // 5,6,7,8,9张图片
        else if (maxColumn == 3) {
            switch (size) {
                case 5:
                    // 对应坐标 w == imgWidth
                    //   w/2,w/2  3w/2,w/2
                    // 0,3w/2  w,3w/2  2w,3w/2
                    for (int i = 0; i < size; i++) {
                        //计算左上角坐标
                        float xleft = 0;
                        float xtop = 0;
                        switch (i) {
                            case 0:
                                xleft = 1 / 2f;
                                xtop = 1 / 2f;
                                break;
                            case 1:
                                xleft = 3 / 2f + paddingPer;
                                xtop = 1 / 2f;
                                break;
                            case 2:
                            case 3:
                            case 4:
                                xleft = i - 2;
                                xtop = 3 / 2f + paddingPer;
                                if (i != 2) {
                                    xleft += (i - 2) * paddingPer;
                                }
                                break;
                        }

                        addPointF(pointFList, imgWidth, xleft, xtop);
                    }
                    break;
                case 6:
                    // 对应坐标 w == imgWidth
                    // 0,w/2   w,w/2   2w,w/2
                    // 0,3w/2  w,3w/2  2w,3w/2
                    for (int i = 0; i < size; i++) {
                        //计算左上角坐标
                        float xleft = 0;
                        float xtop = 0;
                        switch (i) {
                            case 0:
                            case 1:
                            case 2:
                                xleft = i;
                                xtop = 1 / 2f;
                                if (i != 0) {
                                    xleft += (i) * paddingPer;
                                }
                                break;
                            case 3:
                            case 4:
                            case 5:
                                xleft = i - 3;
                                xtop = 3 / 2f + paddingPer;
                                if (i != 3) {
                                    xleft += (i - 3) * paddingPer;
                                }
                                break;
                        }

                        addPointF(pointFList, imgWidth, xleft, xtop);
                    }
                    break;
                case 7:
                    // 对应坐标 w == imgWidth
                    //       w,0
                    // 0,w   w,w   2w,w
                    // 0,2w  w,2w  2w,2w
                    for (int i = 0; i < size; i++) {
                        //计算左上角坐标
                        float xleft = 0;
                        float xtop = 0;
                        switch (i) {
                            case 0:
                                xleft = 1 + paddingPer;
                                xtop = 0;
                                break;
                            case 1:
                            case 2:
                            case 3:
                                xleft = i - 1;
                                xtop = 1 + paddingPer;
                                if (i != 1) {
                                    xleft += (i - 1) * paddingPer;// 除了第一列，依次递增加padding
                                }
                                break;
                            case 4:
                            case 5:
                            case 6:
                                xleft = i - 4;
                                xtop = 2 + (2) * paddingPer;// 最下面一行要加2倍padding
                                if (i != 4) {
                                    xleft += (i - 4) * paddingPer;// 除了第一列，依次递增加padding
                                }
                                break;
                        }

                        addPointF(pointFList, imgWidth, xleft, xtop);
                    }
                    break;
                case 8:
                    // 对应坐标 w == imgWidth
                    //   w/2,0 3w/2,0
                    // 0,w   w,w   2w,w
                    // 0,2w  w,2w  2w,2w
                    for (int i = 0; i < size; i++) {
                        //计算左上角坐标
                        float xleft = 0;
                        float xtop = 0;
                        switch (i) {
                            case 0:
                                xleft = 1 / 2f;
                                xtop = 0;
                                break;
                            case 1:
                                xleft = 3 / 2f + paddingPer;
                                xtop = 0;
                                break;
                            case 2:
                            case 3:
                            case 4:
                                xleft = i - 2;
                                xtop = 1 + paddingPer;
                                if (i != 2) {
                                    xleft += (i - 2) * paddingPer;// 除了第一列，依次递增加padding
                                }
                                break;
                            case 5:
                            case 6:
                            case 7:
                                xleft = i - 5;
                                xtop = 2 + (2) * paddingPer;// 最下面一行要加2倍padding
                                if (i != 5) {
                                    xleft += (i - 5) * paddingPer;// 除了第一列，依次递增加padding
                                }
                                break;
                        }

                        addPointF(pointFList, imgWidth, xleft, xtop);
                    }
                    break;
                case 9:
                    // 对应坐标 w == imgWidth
                    // 0,0   w,0   2w,0
                    // 0,w   w,w   2w,w
                    // 0,2w  w,2w  2w,2w
                    for (int i = 0; i < size; i++) {
                        //计算左上角坐标
                        float xleft = 0;
                        float xtop = 0;
                        switch (i) {
                            case 0:
                            case 1:
                            case 2:
                                xleft = i;
                                xtop = 0;
                                if (i != 0) {
                                    xleft += (i) * paddingPer;
                                }
                                break;
                            case 3:
                            case 4:
                            case 5:
                                xleft = i - 3;
                                xtop = 1 + paddingPer;
                                if (i != 3) {
                                    xleft += (i - 3) * paddingPer;
                                }
                                break;
                            case 6:
                            case 7:
                            case 8:
                                xleft = i - 6;
                                xtop = 2 + (2) * paddingPer;
                                if (i != 6) {
                                    xleft += (i - 6) * paddingPer;
                                }
                                break;
                        }

                        addPointF(pointFList, imgWidth, xleft, xtop);
                    }
                    break;
            }

        }

        return pointFList;
    }

    /**
     * 计算并保存坐标点
     *
     * @param pointFList
     * @param imgWidth
     * @param xleft
     * @param xtop
     */
    private static void addPointF(List<PointF> pointFList, float imgWidth, float xleft, float xtop) {
        float left = imgWidth * xleft;
        float top = imgWidth * xtop;

        PointF pointF = new PointF(left, top);
        pointFList.add(pointF);
    }

    /**
     * 根据图片数计算行数
     *
     * @param size
     * @return
     */
    private static int getMaxRow(int size) {
        int maxRow = 1;
        switch (size) {
            case 1:
            case 2:
                maxRow = 1;
                break;
            case 3:
            case 4:
            case 5:
            case 6:
                maxRow = 2;
                break;
            case 7:
            case 8:
            case 9:
                maxRow = 3;
                break;
        }

        return maxRow;
    }

    /**
     * 根据图片数计算列数
     *
     * @param size 图片数量
     * @return
     */
    private static int getMaxColumn(int size) {
        int maxColumn = 1;
        switch (size) {
            case 1:
                maxColumn = 1;
                break;
            case 2:
            case 3:
            case 4:
                maxColumn = 2;
                break;
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
                maxColumn = 3;
                break;
        }

        return maxColumn;
    }


    /**
     * 进行图片压缩
     *
     * @param bitmap
     * @param widthDp
     * @return
     */
    public static Bitmap getThumbnailBitmap(Bitmap bitmap, int widthDp) {
        Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, widthDp, widthDp);
        return thumbnail;
    }

    /**
     * drawable 转换成bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 保存图片到文件中
     *
     * @param mContext
     * @param bitmap
     * @param desName
     * @return
     * @throws IOException
     */
    public static File saveBitmap2File(Context mContext, Bitmap bitmap, String desName) throws IOException {
        FileOutputStream fOut = null;
        File file = mContext.getExternalFilesDir("Pictures");
        if (!file.exists()) {
            file.mkdirs();
        }

        File saveFile = new File(file, desName + ".png");
        file.createNewFile();

        fOut = new FileOutputStream(saveFile);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);

        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return saveFile;
    }


    /**
     * 在padding>0的情况，设置图片间隙和边框，否则是有边框
     *
     * @param orginBitmap
     * @param color       背景颜色（即边框和间隙颜色）
     * @param padding     图片间隙
     * @return
     */
    private static Bitmap setBgAndBorder(Bitmap orginBitmap, int color, int padding) {

        Paint paint = new Paint();
        paint.setColor(color);

        int addSize = 2 * padding;
        int afwidth = orginBitmap.getWidth() + addSize;
        int afheight = orginBitmap.getHeight() + addSize;

        Bitmap bitmap = Bitmap.createBitmap(afwidth, afheight, orginBitmap.getConfig());
        Canvas canvas = new Canvas(bitmap);
        // canvas.drawColor(color);
        canvas.drawRect(0, 0, afwidth, afheight, paint);
        canvas.drawBitmap(orginBitmap, padding, padding, paint);
        return bitmap;
    }

    /**
     * 给bitmap设置边框
     *
     * @param bitmap 图片源
     * @param color  边框颜色
     * @param size   宽度
     */
    public static Bitmap setBitmapBorder(Bitmap bitmap, int color, int size) {
        Canvas canvas = new Canvas(bitmap);
        Rect rect = canvas.getClipBounds();
        Paint paint = new Paint();
        //设置边框颜色
        paint.setColor(color);
        paint.setStyle(Paint.Style.STROKE);
        //设置边框宽度
        paint.setStrokeWidth(size);
        canvas.drawRect(rect, paint);
        return bitmap;
    }

    /**
     * 进行图片组合
     *
     * @param first     第一张图片
     * @param second    第二张图片
     * @param fromPoint 第二张图片的坐标
     * @return 组合后的图片
     */
    public static Bitmap mixtureBitmap(Bitmap first, Bitmap second, PointF fromPoint) {
        if (first.getWidth() == 0) {
            return first;
        }
        Bitmap newBitmap = Bitmap.createBitmap(first.getWidth(), first.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas cv = new Canvas(newBitmap);
        // 第一张图片从（0,0）位置开始绘制
        cv.drawBitmap(first, 0, 0, null);
        // 第二张图片从指定的坐标绘制
        cv.drawBitmap(second, fromPoint.x, fromPoint.y, null);
        cv.save();//Canvas.ALL_SAVE_FLAG
        cv.restore();
        return newBitmap;
    }

    public static int dp2px(Context context, float dp) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (dp * density + .5f);
    }
}
